﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// “空白页”项模板在 http://go.microsoft.com/fwlink/?LinkId=234238 上有介绍

namespace HomeControllerServer
{
    /// <summary>
    /// 可用于自身或导航至 Frame 内部的空白页。
    /// </summary>
    public sealed partial class MainPage : Page
    {
        TcpHelp tcpListener;

        public MainPage()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// 在此页将要在 Frame 中显示时进行调用。
        /// </summary>
        /// <param name="e">描述如何访问此页的事件数据。Parameter
        /// 属性通常用于配置页。</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            
        }

        private async void btn_Listen_Click_1(object sender, RoutedEventArgs e)
        {
            try
            {
                tcpListener = new TcpHelp();
                await tcpListener.Listen(this.txt_Port.Text);
                tcpListener.ClientConnectEvent += tcpListener_ClientConnectEvent;
                tcpListener.ClientSendEvent += tcpListener_ClientSendEvent;
                this.sp_InfoList.Children.Add(new TextBlock() { Text = System.DateTime.Now.ToString("yyyy-MM-dd:" + "开始监听"), FontSize = 28 });

            }
            catch (Exception ex)
            {
                this.sp_InfoList.Children.Add(new TextBlock() { Text = System.DateTime.Now.ToString("yyyy-MM-dd:" + "报错 " + ex.Message), FontSize = 28 });
            }
        }

        async void tcpListener_ClientSendEvent(object sender, ClientSendEventArgs e)
        {
            await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(() =>
             {
                 this.sp_InfoList.Children.Add(new TextBlock() { Text = System.DateTime.Now.ToString("yyyy-MM-dd:" + "来自" + e.IPAddress + ":" + e.Message), FontSize = 28 });
             }));
        }

        async void tcpListener_ClientConnectEvent(object sender, ClientConnectEventArgs e)
        {
            await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(() =>
            {
                this.sp_InfoList.Children.Add(new TextBlock() { Text = System.DateTime.Now.ToString("yyyy-MM-dd: " + e.IPAddress + " 客户端接入 "), FontSize = 28 });
            }));
        }


        private void btn_Send_Click_1(object sender, RoutedEventArgs e)
        {
            tcpListener.SendMessageForServer(this.txt_Send.Text);
        }
    }
}
